<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
*/

class xFsTools {
    static function fullname($fname) {
        if (in_array(substr($fname, -1), array('/', '\\'))) {
            $fname = substr($fname, 0, -1);
        }
        $fname = array_pop(preg_split('%[\\\\/]%', $fname));
        return $fname;
    }
    static function filetype($path) {
        $mime = self::mime($path);
        $ext  = self::fileext($path);
        if (strpos($mime, 'text')>-1) {
            return 'text';
        }else if ($ext == 'php') {
            return 'text';
        }else if ($ext == 'log') {
            return 'text';
        } elseif (strpos($mime, 'image')>-1) {
            return 'image';
        } else {
            return 'binary';
        }
    }

    static function mime($fname) {
        $ext = self::fileext($fname);
        $mime = @$GLOBALS['mime_by_ext'][$ext];
        if (!$mime) $mime = 'application/octet-stream';
        return $mime;
    }

    public static function list_files(string $directory, boolean $dots = NULL) {
        $directory = self::enc_name($directory);
        $files = array();
        if (($incdir = opendir($directory)) != false) {
            while (false !== ($file = readdir($incdir))) {
                $file = self::dec_name($file);
                if ($dots !== NULL) {
                    if (in_array($file, array('.','..'))) continue;
                }
                $files[] = $file;
            }
        } else {
            return false;
        }
        return $files;
    }

    public static function find_files(string $directory, string $pattern) {
        $directory = self::enc_name($directory);
        $files = array();
        Guardian::check_regexp_safety($pattern);
        if (($incdir = opendir($directory)) != false) {
            while (false !== ($file = readdir($incdir))) {
                $file = self::dec_name($file);
                if (preg_match($pattern, $subject)) {
                    if (in_array($file, array('.','..'))) continue;
                    $files[] = $file;
                }
            }
        }
        return $files;
    }

    public static function filename(string $fname) {
        if (in_array(substr($fname, -1), array('/', '\\'))) {
            $fname = substr($fname, 0, -1);
        }
        $fname = array_pop(preg_split('%[\\\\/]%', $fname));
        if (strpos($fname, '.') > -1) {
            $fname = explode('.', $fname);
            array_pop($fname);
            $fname = implode('.', $fname);
        }
        return $fname;
    }

    public static function fileext(string $file) {
        $ext = array_pop(explode('.', $file));
        return $ext;
    }

    static function copy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755)) {
        $source = self::enc_name($source);
        $dest = self::enc_name($dest);
        $result=false;

        if (is_file($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if (!file_exists($dest)) {
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
                }
                $__dest=$dest."/".basename($source);
            } else {
                $__dest=$dest;
            }
            $result=copy($source, $__dest);
            chmod($__dest,$options['filePermission']);

        } elseif(is_dir($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if ($source[strlen($source)-1]=='/') {
                    //Copy only contents
                } else {
                    //Change parent itself and its contents
                    $dest=$dest.basename($source);
                    @mkdir($dest);
                    chmod($dest,$options['filePermission']);
                }
            } else {
                if ($source[strlen($source)-1]=='/') {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                } else {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                }
            }

            $dirHandle=opendir($source);
            while($file=readdir($dirHandle)) {
                if($file!="." && $file!="..") {
                    if(!is_dir($source."/".$file)) {
                        $__dest=$dest."/".$file;
                    } else {
                        $__dest=$dest."/".$file;
                    }
                    //echo "$source/$file ||| $__dest<br />";
                    $result=self::copy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);

        } else {
            $result=false;
        }
        return $result;
    }

    static function unlink($fileglob) {
        if (is_string($fileglob)) {
            if (is_file($fileglob)) {
                return unlink($fileglob);
            } else if (is_dir($fileglob)) {
                $ok = self::unlink("$fileglob/*");
                if (! $ok) {
                    return false;
                }
                return rmdir($fileglob);
            } else {
                $matching = glob($fileglob);
                if ($matching === false) {
                    trigger_error(sprintf('No files match supplied glob %s', $fileglob), E_USER_WARNING);
                    return false;
                }
                $rcs = array_map(array('FSTools', 'unlink'), $matching);
                if (in_array(false, $rcs)) {
                    return false;
                }
            }
        } else if (is_array($fileglob)) {
            $rcs = array_map(array('FSTools', 'unlink'), $fileglob);
            if (in_array(false, $rcs)) {
                return false;
            }
        } else {
            trigger_error('Param #1 must be filename or glob pattern, or array of filenames or glob patterns', E_USER_ERROR);
            return false;
        }

        return true;
    }

    public static function enc_name($name) {
//        return $name;
        return mb_convert_encoding($name, self::get_fs_enc(), 'utf-8');
    }

    public static function dec_name($name) {
//        return $name;
        return mb_convert_encoding($name, 'utf-8', self::get_fs_enc());
    }

    public static function get_fs_enc() {
        if (!@$_SESSION['fsenc']) {
            $encs = array('cp1251', 'KOI8-R', 'cp866', 'utf8');
            $kodirovka = './etc/кодировка';
            foreach($encs as $enc) {
                if ($enc!='utf8') $k = iconv('utf8', 'cp1251', $kodirovka);
                if (realpath($k)) {
                    $_SESSION['fsenc'] = $enc;
                    break;
                }
            }
        }
        return $_SESSION['fsenc'];
        if(preg_match('%^\w:[\\\\/]%', realpath(__FILE__))) {
            return 'cp1251';
        }
        return 'utf-8';
    }

    public static function rename($from, $to) {
        $from = self::enc_name($from);
        $to = self::enc_name($to);
        rename($from, $to);
    }

    public static function printFile($file) {
        $file = self::enc_name($file);
//        echo $file;
        $h = fopen($file, "rb");
        if (!$h) die('----!!!!');
        while(!feof($h)) {
            echo fread($h,1);
        }
    }

    public static function translit($st) {
        // Сначала заменяем "односимвольные" фонемы.
        $st=strtr($st,"абвгдеёзийклмнопрстуфхъыэ_",
                "abvgdeeziyklmnoprstufhiei");
        $st=strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ_",
                "ABVGDEEZIYKLMNOPRSTUFHIEI");
        // Затем - "многосимвольные".
        $st=strtr($st,
                array(
                "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
                "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
                "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
                "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
                )
        );
        // Возвращаем результат.
        return $st;
    }

    public static function download_name_encode($name) {
        $downname = $name;
        if (stripos($_SERVER['HTTP_USER_AGENT'], 'msie') > -1) {
            $downname = (mb_convert_encoding($name, 'cp1251', 'utf-8'));
        } elseif (stripos($_SERVER['HTTP_USER_AGENT'], 'firefox') > -1) {
//            $downname = '"'.mb_encode_mimeheader(mb_convert_encoding($name, 'cp1251', 'utf-8'), 'cp1251', 'B').'"';
            $downname = '"'.str_replace(' ', '%20', (mb_convert_encoding($name, 'cp1251', 'utf-8'))).'"';
        }
//        die($downname);
        return $downname;
    }

}


?>
